require "benchmark"
require "date"
require "net/http"

API_KEY = ENV['API_KEY']
USER_ACCOUNT = ENV['USER_ACCOUNT']
DEVICE_SET = ENV['DEVICE_SET']
CATEGORY = ENV['CATEGORY']
LOCALE = "en_US"

task :default => ['build:android', 'build:ios', 'build:tests']

desc "Removes bin and obj directories for Android, iOS, and test projects."
task :clean do
	[
		"../../src/MobileApp/XamarinCRM.Android",
		"../../src/MobileApp/XamarinCRM.iOS",
		"./../src/MobileApp/XamarinCRM.UITest",
		"../../src/MobileApp/XamarinCRM.Models"
	].each do |dir|
		rm_rf "#{dir}/bin"
		rm_rf "#{dir}/obj"
	end
end

namespace :build do
	desc "Build Android App"
	task :android => [:restore_packages] do
		# puts "Adding maps to manifest"
		# addMaptoManifest("../../src/MobileApp/XamarinCRM.Android/Properties/AndroidManifest.xml")
		puts "Building XamarinCRM.Android"
		time = time_cmd "xbuild ../../src/MobileApp/XamarinCRM.Android/XamarinCRM.Android.csproj /p:Configuration=Debug /t:SignAndroidPackage /verbosity:quiet /flp:LogFile=build_android.log"

		puts "Checking for Insights on Android"
		sh "cat ../../src/MobileApp/XamarinCRM.Android/MainActivity.cs | grep Insights | grep 2b82ddc37582e6c1bece7e5901e8bae3bf7bfb26"

		size = (File.size("../../src/MobileApp/XamarinCRM.Android/bin/Debug/com.xamarin.xamarincrm-Signed.apk")/1000000.0).round(1)
		log_data "Android", time, size, "build_android.log"
	end

	desc "Build iOS App"
	task :ios => [:restore_packages] do
		puts "Building XamarinCRM.iOS"
  	time = time_cmd "xbuild ../../src/MobileApp/XamarinCRM.sln /p:Configuration='iOS Debug (Development)' /p:Platform=iPhone /p:BuildIpa=true /verbosity:quiet /flp:LogFile=build_ios.log"

		puts "Checking for Insights on iOS"
		sh "cat ../../src/MobileApp/XamarinCRM.iOS/Main.cs | grep Insights | grep 2b82ddc37582e6c1bece7e5901e8bae3bf7bfb26"

 		size = (File.size("../../src/MobileApp/XamarinCRM.iOS/bin/iPhone/Debug/XamarinCRM_Debug.ipa")/1000000.0).round(1)
    log_data "iOS", time, size, "build_ios.log"
	end

	desc "Build Test Solution"
	task :tests => [:restore_packages] do
		puts "Building Test Solution"
		sh "xbuild ../../src/MobileApp/XamarinCRM.UITest/XamarinCRM.UITest.csproj /verbosity:quiet"
	end

	desc "Restores packages for all projects"
  task :restore_packages do
    puts "restoring packages with:"
    sh "nuget restore ../../src/MobileApp/XamarinCRM.sln"
  end

	def time_cmd(cmd)
		time = Benchmark.realtime do
			sh cmd
		end
		min = (time / 60).to_i.to_s
		sec = (time % 60).to_i.to_s
		sec = sec.length < 2 ? "0" + sec : sec
		return "#{min}:#{sec}"
	end

	def log_data(platform, time, size, log_file)
		date = DateTime.now.strftime("%m/%d/%Y %I:%M%p")
		version = /\d+\.\d+\.\d+\.\d+/.match(`mdls -name kMDItemVersion /Applications/Xamarin\\ Studio.app`)
		user = /\w+$/.match(ENV['HOME'])[0].capitalize

		tail = `tail -n 6 #{log_file}`
		warnings = /(\d+) Warning\(s\)/.match(tail).captures[0]
		errors = /(\d+) Error\(s\)/.match(tail).captures[0]

		puts "*** origin: #{user}"
    puts "*** xamarin version: #{version}"
    puts "*** platform: #{platform}"
    puts "*** date time: #{date}"
    puts
    puts "*** build time: #{time}"
    puts "*** app size (MB): #{size}"
    puts "*** warnings: #{warnings}"
    puts "*** errors: #{errors}"

		post_to_sheet("XamarinCRM", date, platform, user, version, size, time, warnings, errors)
  end

  def post_to_sheet(app, date, platform, channel, version, size, time, warnings, errors)
    uri = URI("https://script.google.com/macros/s/AKfycbzlrwTXjCjOHY64uOIF3C1yg1GYDpvK8XXcDBfX68c6YhkL21M/exec")
    params = {
      method: 'writeLine',
      app: app,
      date: date,
      platform: platform,
      channel: channel,
      version: version,
      size:size,
      time: time,
      warnings: warnings,
      errors: errors
    }

    res = Net::HTTP.post_form(uri, params)
    if res.code == "302"
      res = Net::HTTP.get_response(URI(res.header['location']))
    end
    raise res.body unless res.is_a?(Net::HTTPSuccess)

    puts res.body
  end

	def addMaptoManifest(xml_file)
	  xml_text = File.read(xml_file)

	  newContent = xml_text.gsub("\t\t<meta-data android:name=\"com.google.android.maps.v2.API_KEY\" android:value=\"@string/GoogleMapsKey\" />\n",
	      "\t\t<meta-data android:name=\"com.google.android.maps.v2.API_KEY\" android:value=\"AIzaSyBmRuR-M2PV8bF_ljjAQBNzkzSDpmkStfI\" />\n")

	  File.open(xml_file, "w"){|newFile| newFile.puts newContent}
	end
end

namespace :testcloud do
	desc "Push Android tests to XTC"
	task :android => ['build:tests'] do
		get_env_variables
		devices = get_device_code(DEVICE_SET, "android")
		unless CATEGORY.nil?
			sh "mono ../../src/MobileApp/packages/Xamarin.UITest.1.2.0/tools/test-cloud.exe submit ../../src/MobileApp/XamarinCRM.Android/bin/Debug/*Signed.apk #{API_KEY} --devices #{devices} --series \"#{DEVICE_SET}\" --locale #{LOCALE} --app-name \"Xamarin CRM\" --user #{USER_ACCOUNT} --assembly-dir ../../src/MobileApp/XamarinCRM.UITest/bin/Debug --category #{CATEGORY}" # keystore ~/.android/debug.keystore android androiddebugkey android
		else
			sh "mono ../../src/MobileApp/packages/Xamarin.UITest.1.2.0/tools/test-cloud.exe submit ../../src/MobileApp/XamarinCRM.Android/bin/Debug/*Signed.apk #{API_KEY} --devices #{devices} --series \"#{DEVICE_SET}\" --locale #{LOCALE} --app-name \"Xamarin CRM\" --user #{USER_ACCOUNT} --assembly-dir ../../src/MobileApp/XamarinCRM.UITest/bin/Debug" # keystore ~/.android/debug.keystore android androiddebugkey android
		end
	end

	desc "Push iOS tests to XTC"
	task :ios => ['build:tests'] do
		get_env_variables
		devices = get_device_code(DEVICE_SET, "ios")
		unless CATEGORY.nil?
 			sh "mono ../../src/MobileApp/packages/Xamarin.UITest.1.2.0/tools/test-cloud.exe submit ../../src/MobileApp/XamarinCRM.iOS/bin/iPhone/Debug/*.ipa #{API_KEY} --devices #{devices} --series \"#{DEVICE_SET}\" --locale #{LOCALE} --app-name \"Xamarin CRM\" --user #{USER_ACCOUNT} --assembly-dir ../../src/MobileApp/XamarinCRM.UITest/bin/Debug --dsym ../../src/MobileApp/XamarinCRM.iOS/bin/iPhone/Debug/*.app.dSYM --category #{CATEGORY}"
		else
			sh "mono ../../src/MobileApp/packages/Xamarin.UITest.1.2.0/tools/test-cloud.exe submit ../../src/MobileApp/XamarinCRM.iOS/bin/iPhone/Debug/*.ipa #{API_KEY} --devices #{devices} --series \"#{DEVICE_SET}\" --locale #{LOCALE} --app-name \"Xamarin CRM\" --user #{USER_ACCOUNT} --assembly-dir ../../src/MobileApp/XamarinCRM.UITest/bin/Debug --dsym ../../src/MobileApp/XamarinCRM.iOS/bin/iPhone/Debug/*.app.dSYM"
		end
	end

	def get_env_variables
		arguments = ["API_KEY", "USER_ACCOUNT", "DEVICE_SET"]

		[API_KEY, USER_ACCOUNT, DEVICE_SET].each_with_index do |val, index|
			if val.nil?
				raise "#{arguments[index]} cannot be nil, please input a value."
			end
		end
	end

	def get_device_code device_set, platform
		case platform
		when "android"
			case device_set
			when "Small"
				return 'fe5e138d'
			when "Medium"
				return 'fba3c414'
			when "Large"
				return "ac078209"
			end
		when "ios"
			case device_set
			when "Small"
				return '2f802e3f'
			when "Medium"
				return '6755343a'
			when "Large"
				return 'e1df384a'
			end
		end
	end
end
